package com.kaiwukj.android.ufamily.mvp.ui.page.home.home;

import android.content.Context;
import android.graphics.Color;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.ctetin.expandabletextviewlibrary.ExpandableTextView;
import com.kaiwukj.android.mcas.http.imageloader.glide.GlideArms;
import com.kaiwukj.android.mcas.utils.McaUtils;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.MyApplication;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.CommentResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.DynamicResult;
import com.kaiwukj.android.ufamily.mvp.ui.adapter.NineGridIvAdapter;
import com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.SocialCircleActivity;
import com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.detail.DynamicDetailFragment;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.NineGridView;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class DynamicAdapter extends BaseQuickAdapter<DynamicResult, DynamicAdapter.ViewHolder> {

    private int index = 0;

    public void setIndex() {
        index = 1;
    }

    public int getPositionById(int id) {
        for (int i = 0; i < getData().size(); i++) {
            if (getData().get(i).getId() == id) {
                return i;
            }
        }
        return -1;
    }

    public DynamicAdapter(@Nullable List<DynamicResult> data) {
        super(R.layout.item_dynamic, data);
        addChildClickViewIds(R.id.container_good, R.id.container_comment, R.id.container_action_more, R.id.view_comment, R.id.btn_attention);
    }

    @Override
    public long getItemId(int position) {
        DynamicResult result = getItem(position);
        return result == null ? -1 : result.getId();
    }


    public long getLastItemId() {
        if (getData().size() == 0) return 0;
        return getItemId(getData().size() - 1);
    }

    public void postLike(boolean like, int position) {
        getItem(position).praise(like);
        int oldCount = getItem(position).getThumbNum();
        if (like) {
            getItem(position).setThumbNum(++oldCount);
        } else {
            if (oldCount > 0) {
                getItem(position).setThumbNum(--oldCount);
            }
        }
        notifyItemChanged(position, "postLike");
    }

    public void postAttention(int position, boolean attention) {
        getItem(position).attention(attention);
        notifyItemChanged(position, "postAttention");
    }

    public void postAttentionByUserId(int userId, boolean attention) {
        for (int i = 0; i < getData().size(); i++) {
            if (userId == getItem(i).getUserId()) {
                postAttention(i, attention);
            }
        }
    }

    public void postComment(int position, CommentResult result) {
        ViewHolder viewHolder = (ViewHolder) getRecyclerView().findViewHolderForAdapterPosition(position);
        if (viewHolder != null) {
            viewHolder.addComment(result);
        }
        int oldCount = getItem(position).getCommentNum();
        getItem(position).setCommentNum(++oldCount);
        notifyItemChanged(position, "postComment");
    }

    public void setNewCommentData(int position, List<CommentResult> results) {
        ViewHolder viewHolder = (ViewHolder) getRecyclerView().findViewHolderForAdapterPosition(position);
        if (viewHolder != null) {
            viewHolder.setNewData(results);
        }
        int oldCount = getItem(position).getCommentNum();
        if (oldCount > 0) {
            getItem(position).setCommentNum(--oldCount);
        }
        notifyItemChanged(position, "postComment");
        // notifyItemChanged(position);
    }

    /**
     * 屏蔽用户建议直接重新拉取数据
     *
     * @param userId userId
     */
    @Deprecated
    public void blockUser(int userId) {
        for (int i = 0; i < getData().size(); i++) {
            if (userId == getData().get(i).getUserId()) {
                removeAt(i);
            }
        }
    }

    public void blockDynamic(int dynamicId) {
        removeAt(getPositionById(dynamicId));
    }


    @Override
    protected void convert(@NotNull ViewHolder holder, DynamicResult item, @NotNull List<?> payloads) {

        LogUtils.d("payLoads------------------>" + GsonUtils.toJson(payloads));
        if (payloads.isEmpty()) {
            super.convert(holder, item, payloads);
        } else {
            String tag = (String) payloads.get(0);
            if ("postLike".equals(tag)) {
                //ImageView ivGood = holder.getView(R.id.iv_good);
                //.  TextView tvGoodNum = holder.getView(R.id.tv_good_num);
                if (item.isPraise()) {
                    holder.setImageResource(R.id.iv_good, R.mipmap.ic_dynamic_good_checked);
                    //  ivGood.setImageResource(R.mipmap.ic_dynamic_good_checked);
                } else {
                    holder.setImageResource(R.id.iv_good, R.mipmap.ic_dynamic_good);
                    // tvGoodNum.setCompoundDrawables(getContext().getDrawable(R.mipmap.ic_dynamic_good), null, null, null);
                    // ivGood.setImageResource(R.mipmap.ic_dynamic_good);
                }
                //tvGoodNum.setText(String.valueOf(getItem(position).getThumbNumText()));
                holder.setText(R.id.tv_good_num, item.getThumbNumText());
            } else if ("postComment".equals(tag)) {
                holder.setText(R.id.tv_comment_num, item.getCommentNumText());
            } else if ("postAttention".equals(tag)) {
                LogUtils.d("postAttention------------------>" + item.isAttention());
                holder.setVisible(R.id.btn_attention, !item.isAttention());
            }
        }
    }

    @NotNull
    @Override
    protected ViewHolder createBaseViewHolder(@NotNull View view) {
        return new ViewHolder(view);
    }

    @Override
    protected void convert(ViewHolder helper, DynamicResult item) {

        ImageView ivGood = helper.getView(R.id.iv_good);
        if (item.isPraise()) {
            ivGood.setImageResource(R.mipmap.ic_dynamic_good_checked);
        } else {
            ivGood.setImageResource(R.mipmap.ic_dynamic_good);
        }

        //Placeholder placeholder = helper.getView(R.id.place_holder);
        helper.setVisible(R.id.btn_attention, !item.isAttention() && !item.getUserId().equals(MyApplication.getInstance().getUserInfo().getId()));
        QMUIRoundButton btnTag = helper.getView(R.id.tag);

        // addChildClickViewIds(R.id.iv_avatar, R.id.iv_video_play);

        helper.itemView.setOnClickListener(v ->
                ARouter.getInstance().build(ARouterUrlKt.SocialCircleUrl)
                        .withString(SocialCircleActivity.FRAGMENT_KEY, DynamicDetailFragment.CIRCLE_CARD_DETAIL)
                        //.withSerializable(SocialCircleActivity.FRAGMENT_KEY_CARD_BEAN, item)
                        .withInt("dynamicId", item.getId())
                        // .withInt("itemPos", helper.getAdapterPosition())
                        .navigation());
        helper.getView(R.id.iv_avatar).setOnClickListener(v ->
                ARouter.getInstance().build(ARouterUrlKt.DynamicPersonUrl)
                        .withInt("userId", item.getUserId())
                        .navigation());

        ViewGroup cagGroup = helper.getView(R.id.container_group_cag);


        if (index == 1) {
            //  placeholder.setContentId(R.id.container_group_cag);
            btnTag.setVisibility(View.GONE);
        } else {
            btnTag.setOnClickListener(v -> ARouter.getInstance()
                    .build(ARouterUrlKt.TopicIndexUrl)
                    .withInt("topicId", item.getTopicId())
                    .navigation());
        }

        if (StringUtils.isEmpty(item.getTopicTitle())) {
            btnTag.setVisibility(View.GONE);
        }

        Glide.with(getContext())
                .load(item.getHeadImg())
                .into((ImageView) helper.getView(R.id.iv_avatar));

        helper.setText(R.id.tv_user_name, item.getUserName());

        String publishTime = TimeUtils.getFriendlyTimeSpanByNow(item.getCreateTime());
        String communityName = item.getCommunityName();
        SpannableString spanString = new SpannableString(String.format("%s 来自%s", publishTime, communityName));
        spanString.setSpan(new ForegroundColorSpan(Color.parseColor("#3A82C4")),
                spanString.length() - communityName.length(), spanString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        helper.setText(R.id.tv_user_community, spanString);
        //helper.setText(R.id.tv_note, item.getDynamicContent());
        ExpandableTextView tvNote = helper.getView(R.id.tv_note);
        tvNote.setContent(item.getDynamicContent());
        helper.setText(R.id.tag, item.getTopicTitle());
        helper.setText(R.id.tv_comment_num, item.getCommentNumText());
        helper.setText(R.id.tv_good_num, item.getThumbNumText());

        ViewGroup containerMedia = helper.getView(R.id.container_media);
        NineGridView containerImage = helper.getView(R.id.container_image);
        ViewGroup containerVideo = helper.getView(R.id.container_video);

        if (StringUtils.isEmpty(item.getImages()) && StringUtils.isEmpty(item.getVideo())) {
            containerMedia.setVisibility(View.GONE);
        } else {
            containerMedia.setVisibility(View.VISIBLE);
            if (!StringUtils.isEmpty(item.getVideo())) {
                //91360111MA38CD9D4M
                //江西省开物科技有限公司
                //  LogUtils.d("url------------->" + item.getImage());
                //存在视频
                ImageView ivVideoCover = helper.getView(R.id.iv_video_cover);
                GlideArms.with(getContext())
                        .load(item.getImages())
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(ivVideoCover);
                containerImage.setVisibility(View.GONE);
                containerVideo.setVisibility(View.VISIBLE);
                helper.getView(R.id.iv_video_play).setOnClickListener(v -> {
                    ARouter.getInstance().build(ARouterUrlKt.VideoPlay)
                            .withString("videoUrl", item.getVideo())
                            .withString("coverUrl", item.getImages())
                            .withString("title", item.getDynamicContent())
                            //.withString(ExtraCons.EXTRA_KEY_VIDEO_DATA, new Gson().toJson(new DynamicCollection(getData())))
                            //.withInt("noteId", item.getId())
                            //.withString(ExtraCons.EXTRA_KEY_EDIT_MINE, PersonHomePageFragment.PERSON_HOME_PAGE_FRAGMENT)
                            .navigation(getContext());
                });
                //  addChildClickViewIds(R.id.iv_video_play);
            } else {
                //图文
                List<String> imageList = Arrays.asList(item.getImages().split(","));
                initGroupImageAdapter(imageList, containerImage);
                containerVideo.setVisibility(View.GONE);
                containerImage.setVisibility(View.VISIBLE);
            }
        }

        helper.init(getContext(), item.getCommentList());

        /*if (item.getCommentList() == null || item.getCommentList().isEmpty()) {
            helper.groupComment.setVisibility(View.GONE);
        } else {
            helper.groupComment.setVisibility(View.VISIBLE);
        }*/

        /*helper.footerView.setOnClickListener(v ->
                ARouter.getInstance().build(ARouterUrlKt.SocialCircleUrl)
                        .withString(SocialCircleActivity.FRAGMENT_KEY, DynamicDetailFragment.CIRCLE_CARD_DETAIL)
                        //.withSerializable(SocialCircleActivity.FRAGMENT_KEY_CARD_BEAN, item)
                        .withInt("dynamicId", item.getId())
                        // .withInt("itemPos", helper.getAdapterPosition())
                        .navigation());*/
    }

    /**
     * @param imageList
     * @param mImageGroup
     */
    private void initGroupImageAdapter(List<String> imageList, NineGridView mImageGroup) {
        ArrayList<ImageInfo> imageInfo = new ArrayList<>();
        for (int i = 0; i < imageList.size(); i++) {
            ImageInfo info = new ImageInfo();
            info.setThumbnailUrl(imageList.get(i));
            info.setBigImageUrl(imageList.get(i));
            imageInfo.add(info);
        }
        //单张图片的大小
        NineGridIvAdapter mGridIvAdapter = new NineGridIvAdapter(getContext(), imageInfo);
        mImageGroup.setSingleImageSize(McaUtils.getScreenWidth(getContext()) / 2);
        mImageGroup.setAdapter(mGridIvAdapter);
    }

    public static class ViewHolder extends BaseViewHolder {
        // public CommentNormalAdapter commentAdapter;
        //  public Group groupComment;
        //  public RecyclerView rvComment;
        private View footerView;

        public ViewHolder(@NotNull View view) {
            super(view);
            // groupComment = view.findViewById(R.id.group_comment);
            // rvComment = view.findViewById(R.id.rv_comment);
        }

        public void init(Context context, List<CommentResult> commentResults) {

        /*    rvComment.setLayoutManager(new LinearLayoutManager(context));
            if (rvComment.getItemDecorationCount() == 0) {
                rvComment.addItemDecoration(new SpaceItemDecoration(10));
            }

            commentAdapter = new CommentNormalAdapter(commentResults == null ? new ArrayList<>() : commentResults);
            footerView = View.inflate(context, R.layout.item_comments_footer, null);
            commentAdapter.addFooterView(footerView);
            rvComment.setAdapter(commentAdapter);

            if (commentAdapter.getItemCount() <= 0) {
                groupComment.setVisibility(View.GONE);
            }*/

        }

        public void addComment(CommentResult result) {
           /* if (commentAdapter != null) {
                commentAdapter.addNewComment(result);
                if (commentAdapter.getItemCount() <= 0) {
                    groupComment.setVisibility(View.GONE);
                } else {
                    groupComment.setVisibility(View.VISIBLE);
                }
            }*/
        }

        public void setNewData(List<CommentResult> results) {
            LogUtils.d("results-------------------->" + GsonUtils.toJson(results));
           /* if (commentAdapter != null) {
                commentAdapter.setList(results);
                if (commentAdapter.getItemCount() <= 0) {
                    groupComment.setVisibility(View.GONE);
                } else {
                    groupComment.setVisibility(View.VISIBLE);
                }
            }*/
        }
    }
}
